package com.bill.gaty.mfidelity.activities;

import java.util.LinkedHashMap;

import java.util.Map.Entry;
import java.util.Set;

import com.bill.gaty.mfidelity.R;

import com.bill.gaty.mfidelity.beans.Gtf;

import com.bill.gaty.mfidelity.dao.impl.GtfDaoImpl;
import com.bill.gaty.mfidelity.dao.impl.SecurityDaoImpl;
import com.bill.gaty.mfidelity.dto.GtfResponse;
import com.bill.gaty.mfidelity.dto.SauvegardeRestaurationResponse;
import com.bill.gaty.mfidelity.type.GtfResponseType;
import com.bill.gaty.mfidelity.type.SexeType;
import com.bill.gaty.mfidelity.webservices.WebService;
import com.google.gson.Gson;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import android.os.Bundle;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;

import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TextView;
import android.widget.Toast;

public class GtfActivity extends Activity {
	private SexeType sexe;
	private int indexGlabalQuestion;
	private LinkedHashMap<String, String> responses;
	private LinkedHashMap<Integer, GtfResponse> UserResponses;
	 private AlertDialog.Builder adb;
	 private String votrenom,nomdevotremai;
	private LinkedHashMap<Integer, String> questions;
	private RadioGroup radioGroup_choix_sexe, radioGroup_reponses;
	private Gtf gtf;
	private String reponse;
private EditText sauvegarde_edittext_nom_de_votre_ami,
sauvegarde_edittext_votrenom,sauvegarde_edittext_password,sauvegarde_edittext_username;
	private RadioButton sexe_feminin_radio_button, sexe_masculin_radio_button,
			reponse_gtf_oui, reponse_gtf_non, reponse_gtf_peut_etre;

	private LinearLayout LinearLayout_zone_reponse,
			LinearLayout_affichage_resultat;
	private TextView zone_affichage_TextView, zone_affichage_resultat_TextView;

	private Button zone_reponse_button_precedent,
			zone_affichage_resultat_button_sauvegarder,
			zone_affichage_resultat_button_quitter;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.gtf_activity_layout);
		radioGroup_choix_sexe = (RadioGroup) findViewById(R.id.radioGroup_choix_sexe);
		radioGroup_reponses = (RadioGroup) findViewById(R.id.radioGroup_reponses);
		sexe_feminin_radio_button = (RadioButton) findViewById(R.id.sexe_feminin_radio_button);
		sexe_masculin_radio_button = (RadioButton) findViewById(R.id.sexe_masculin_radio_button);
		reponse_gtf_oui = (RadioButton) findViewById(R.id.reponse_gtf_oui);
		reponse_gtf_non = (RadioButton) findViewById(R.id.reponse_gtf_non);
		reponse_gtf_peut_etre = (RadioButton) findViewById(R.id.reponse_gtf_peut_etre);
		LinearLayout_zone_reponse = (LinearLayout) findViewById(R.id.LinearLayout_zone_reponse);
		LinearLayout_affichage_resultat = (LinearLayout) findViewById(R.id.LinearLayout_affichage_resultat);
		zone_affichage_TextView = (TextView) findViewById(R.id.zone_affichage_TextView);
		zone_affichage_resultat_TextView = (TextView) findViewById(R.id.zone_affichage_resultat_TextView);
		zone_reponse_button_precedent = (Button) findViewById(R.id.zone_reponse_button_precedent);
		zone_affichage_resultat_button_sauvegarder = (Button) findViewById(R.id.zone_affichage_resultat_button_sauvegarder);
		zone_affichage_resultat_button_quitter = (Button) findViewById(R.id.zone_affichage_resultat_button_quitter);

		LinearLayout_affichage_resultat.setVisibility(View.INVISIBLE);
		LinearLayout_zone_reponse.setVisibility(View.INVISIBLE);
		 
		 
		radioGroup_choix_sexe
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						if (checkedId != -1) {
							LinearLayout_affichage_resultat.setVisibility(View.INVISIBLE);
							
							if (checkedId == sexe_feminin_radio_button.getId())
								sexe = SexeType
										.fromString(sexe_feminin_radio_button
												.getText().toString());
							else if (checkedId == sexe_masculin_radio_button
									.getId())
								sexe = SexeType
										.fromString(sexe_masculin_radio_button
												.getText().toString());
							initialize();
						}
					}
				});
	}

	public void initialize() {
		questions = new LinkedHashMap<Integer, String>();
		responses = new LinkedHashMap<String, String>();
		String[] qs, reps, clefrep = getResources().getStringArray(
				R.array.reponses_number);
		;
		if (sexe == SexeType.FEMININ) {
			qs = getResources().getStringArray(R.array.questions_femme);
			reps = getResources().getStringArray(R.array.reponses_femme);
		} else {
			qs = getResources().getStringArray(R.array.questions_homme);
			reps = getResources().getStringArray(R.array.reponses_homme);
		}
		for (int j = 0; j < clefrep.length; j++) {
			responses.put(clefrep[j], reps[j]);
			Log.i("initialize.responses", clefrep[j] + "=" + reps[j]);
		}
		for (int j = 0; j < qs.length; j++) {
			questions.put((j + 1), qs[j]);
			Log.i("initialize.questions", (j + 1) + "=" + qs[j]);
		}
		indexGlabalQuestion = 1;
		LinearLayout_zone_reponse.setVisibility(View.VISIBLE);
		startGame();
	}

	public void startGame() {
		UserResponses = new LinkedHashMap<Integer, GtfResponse>();
		radioGroup_reponses
				.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {

					@Override
					public void onCheckedChanged(RadioGroup group, int checkedId) {
						// TODO Auto-generated method stub
						if (checkedId != -1) {
							GtfResponse rep = null;
							if (UserResponses.containsKey(indexGlabalQuestion))
								rep = UserResponses.get(indexGlabalQuestion);
							else
								rep = new GtfResponse();
							rep.setNumero(indexGlabalQuestion);
							rep.setQuestion(questions.get(indexGlabalQuestion));
							if (checkedId == reponse_gtf_oui.getId()) {
								rep.setReponse(GtfResponseType
										.fromString("OUI"));
								reponse_gtf_oui.setChecked(false);
							} else if (checkedId == reponse_gtf_peut_etre
									.getId()) {
								rep.setReponse(GtfResponseType
										.fromString("PEUT_ETRE"));
								reponse_gtf_peut_etre.setChecked(false);
							} else {
								rep.setReponse(GtfResponseType
										.fromString("NON"));
								reponse_gtf_non.setChecked(false);
							}
							indexGlabalQuestion++;
							UserResponses.put(rep.getNumero(), rep);
							setQuestion();

						}
					}
				});
		zone_reponse_button_precedent
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						
						indexGlabalQuestion--;
						if (indexGlabalQuestion <= 0)
							indexGlabalQuestion = 1;
						Log.e("zone_reponse_button_precedent.setOnClickListener",indexGlabalQuestion+"");
						setQuestion();
					}
				});
		setQuestion();
	}

	public void setQuestion() {
		  if (indexGlabalQuestion > questions.size())
			afficherResultat();
		  else if(UserResponses.size()>0&&UserResponses.get(1)!=null&&UserResponses.get(1).getReponse()==GtfResponseType.NON)
			{UserResponses.remove(1);
			  afficherResultat();
			}
		else if(indexGlabalQuestion==11&&UserResponses.get(10).getReponse()!=GtfResponseType.OUI){
			
			GtfResponse r=UserResponses.get(indexGlabalQuestion);
			if(null==r)r=new GtfResponse();
			r.setNumero(indexGlabalQuestion);
			r.setQuestion(questions.get(indexGlabalQuestion));
			r.setReponse(GtfResponseType.NON);
			UserResponses.put(indexGlabalQuestion, r);
			indexGlabalQuestion++;
			setQuestion() ;
		}
else if(indexGlabalQuestion==14&&UserResponses.get(13).getReponse()==GtfResponseType.NON){
			
			GtfResponse r=UserResponses.get(indexGlabalQuestion);
			if(null==r)r=new GtfResponse();
			r.setNumero(indexGlabalQuestion);
			r.setQuestion(questions.get(indexGlabalQuestion));
			r.setReponse(GtfResponseType.NON);
			UserResponses.put(indexGlabalQuestion, r);
			indexGlabalQuestion++;
			setQuestion() ;
		}
else if(indexGlabalQuestion==22&&UserResponses.get(21).getReponse()==GtfResponseType.NON){
	
	GtfResponse r=UserResponses.get(indexGlabalQuestion);
	if(null==r)r=new GtfResponse();
	r.setNumero(indexGlabalQuestion);
	r.setQuestion(questions.get(indexGlabalQuestion));
	r.setReponse(GtfResponseType.NON);
	UserResponses.put(indexGlabalQuestion, r);
	indexGlabalQuestion++;
	setQuestion() ;
}

		else {
			String quest = questions.get(indexGlabalQuestion);
			zone_affichage_TextView.setText(quest);
			// if(UserResponses.containsKey(indexGlabalQuestion)){
			// GtfResponse r=UserResponses.get(indexGlabalQuestion);
			//
			// }

		}
	}

	public String computeResult() {
		int oui = 0, non = 0, peut = 0;
		Set<Entry<Integer, GtfResponse>> ent = UserResponses.entrySet();
		for (Entry<Integer, GtfResponse> entry : ent) {
			GtfResponse r = entry.getValue();
			if (r.getReponse() == GtfResponseType.OUI)
				oui++;
			else if (r.getReponse() == GtfResponseType.PEUT_ETRE)
				peut++;
			else
				non++;
		}
		String res = ((oui % 3) + "" + (non % 3) + "" + (peut % 3)).trim();
		Log.e("computeResult", res);
		return res;

	}

	public void afficherResultat() {
		LinearLayout_affichage_resultat.setVisibility(View.VISIBLE);
		zone_affichage_resultat_button_sauvegarder
		.setVisibility(View.VISIBLE);
		String coderesultat = computeResult();
reponse=responses.get(coderesultat);
		zone_affichage_resultat_TextView.setText(responses.get(coderesultat));

		zone_affichage_resultat_button_sauvegarder
				.setOnClickListener(new View.OnClickListener() {

					@SuppressLint("ShowToast")
					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						zone_affichage_resultat_button_sauvegarder
								.setVisibility(View.GONE);
						 
						Log.i("zone_affichage_resultat_button_sauvegarder.setVisibility(View.GONE)","entering ...");
						
						 adb = new AlertDialog.Builder(GtfActivity.this);
							adb.setTitle(getResources().getString(R.string.label_sauvegarde));
							View vv=getView(R.layout.sauvegarde_layout);
							Log.i("View vv",""+vv);
							 
							adb.setIcon(R.drawable.ic_launcher);
							sauvegarde_edittext_nom_de_votre_ami=(EditText) vv.findViewById(R.id.sauvegarde_edittext_nom_de_votre_ami);
							sauvegarde_edittext_votrenom=(EditText) vv.findViewById(R.id.sauvegarde_edittext_votrenom);
							
							SharedPreferences share = getPreferences(MODE_PRIVATE);
							sauvegarde_edittext_nom_de_votre_ami.setText(share.getString("sauvegarde_edittext_nom_de_votre_ami", ""));
							sauvegarde_edittext_votrenom.setText(share.getString("sauvegarde_edittext_votrenom", ""));
							
							
							adb.setView(vv);
							adb.setNegativeButton(R.string.label_annuler, new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									zone_affichage_resultat_button_sauvegarder
									.setVisibility(View.VISIBLE);
							
								}
							});
							adb.setPositiveButton(R.string.label_valider, new DialogInterface.OnClickListener() {
								
								@Override
								public void onClick(DialogInterface dialog, int which) {
									// TODO Auto-generated method stub
									votrenom=sauvegarde_edittext_votrenom.getText().toString();
											nomdevotremai=sauvegarde_edittext_nom_de_votre_ami.getText().toString();
									if(null==votrenom||null==nomdevotremai||votrenom.trim()==""||nomdevotremai.trim()=="")
										adb.show();
									else{
										SharedPreferences share = getPreferences(MODE_PRIVATE);
										Editor edit=share.edit();
										edit.putString("sauvegarde_edittext_nom_de_votre_ami", nomdevotremai);
										edit.putString("sauvegarde_edittext_votrenom", votrenom);
										edit.commit();
										 
										gtf = GtfResponse.toGtf(UserResponses);
										gtf.setReponse(reponse);
										gtf.setNomDeVotreAmi(nomdevotremai);
										gtf.setVotreNom(votrenom);
										adb = new AlertDialog.Builder(GtfActivity.this);
										adb.setTitle(getResources().getString(R.string.label_sauvegarde));
										 adb.setMessage(getResources().getString(R.string.question_sauvegarder_dans_le_cloud));
										adb.setIcon(R.drawable.ic_launcher);
										
										 adb.setPositiveButton (R.string.oui, new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												
												 adb = new AlertDialog.Builder(GtfActivity.this);
													adb.setTitle(getResources().getString(R.string.label_sauvegarde));
													View vv=getView(R.layout.sauvegarde_credential_layout);
													 adb.setView(vv);
													adb.setIcon(R.drawable.ic_launcher);
													sauvegarde_edittext_password=(EditText) vv.findViewById(R.id.sauvegarde_edittext_password);
													sauvegarde_edittext_username=(EditText) vv.findViewById(R.id.sauvegarde_edittext_username);
													
													SharedPreferences share = getPreferences(MODE_PRIVATE);
													sauvegarde_edittext_password.setText(share.getString("sauvegarde_edittext_password", null));
													sauvegarde_edittext_username.setText(share.getString("sauvegarde_edittext_username", null));
													 
													adb.setNegativeButton(R.string.label_annuler, new DialogInterface.OnClickListener() {
														
														
														
														
														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															zone_affichage_resultat_button_sauvegarder
															.setVisibility(View.VISIBLE);
													
														}
													});
												
													adb.setPositiveButton(R.string.label_valider,new DialogInterface.OnClickListener() {
														
														@Override
														public void onClick(DialogInterface dialog, int which) {
															// TODO Auto-generated method stub
															Thread traitement=new Thread(new Runnable() {
																
																@Override
																public void run() {
																	// TODO Auto-generated method stub
																	SecurityDaoImpl sd=new SecurityDaoImpl(getApplication());
																	sd.open();
																	gtf=sd.getSecureGtf(gtf);
																	sd.close();
																	
																	Gson g=new  Gson();
																	String data=g.toJson(gtf, Gtf.class);
																	String password=sauvegarde_edittext_password.getText().toString().trim();
																	String username=sauvegarde_edittext_username.getText().toString().trim();
																	
																	SharedPreferences share = getPreferences(MODE_PRIVATE);
																	 
																	Editor edit=share.edit();
																	edit.putString("sauvegarde_edittext_password", password);
																	edit.putString("sauvegarde_edittext_username", username);
																	edit.commit();
																	Log.i("String data=g.toJson(gtf, Gtf.class)",data);
																	try{
																	SauvegardeRestaurationResponse resultatssauvegard = WebService.storeGtf(username, password, gtf);
																
																	if(null!=resultatssauvegard)
																	Log.i(" resultatssauvegard",resultatssauvegard.toString()+"");
																	}catch (Exception e) {
																		// TODO: handle exception
																		Log.e("resultatssauvegard",e.getMessage());
																	}
																	
																	Thread.yield();
																}
															});
															Toast.makeText(getApplicationContext(), getResources().getString(R.string.label_info_sauvegarde_en_clod), Toast.LENGTH_SHORT);
															traitement.start();
															while(traitement.isAlive()){}
															zone_affichage_resultat_button_sauvegarder
															.setVisibility(View.VISIBLE);
														}
													});
													adb.show();
												
											}
										});
										 adb.setNegativeButton(R.string.non, new DialogInterface.OnClickListener() {
											
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// TODO Auto-generated method stub
												Toast.makeText(getApplicationContext(),
														getResources().getString(R.string.label_info_sauvegarde_en_local),
														Toast.LENGTH_LONG);
												GtfDaoImpl d = new GtfDaoImpl(getApplicationContext());
												
												
												Log.i(" Gtf res=", gtf.toString());
												d.open();
												d.add(gtf);
												d.close();
												zone_affichage_resultat_button_sauvegarder
														.setVisibility(View.VISIBLE);
												
											}
										});
										 adb.show();
									}
									
								}
							});
							
							
							
						
							adb.show();
						 
						
						
						
					}
				});
		zone_affichage_resultat_button_quitter
				.setOnClickListener(new View.OnClickListener() {

					@Override
					public void onClick(View v) {
						// TODO Auto-generated method stub
						finish();
					}
				});
	}

	@Override
	public void finish() {
		// TODO Auto-generated method stub

		super.finish();
	}
public View getView(int viewlayout){
	LayoutInflater ltInflater = getLayoutInflater();
	return ltInflater.inflate(viewlayout, null, false);
}
}
